﻿using System;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using iTextSharp.text;
using iTextSharp.text.pdf;
using OfficeOpenXml;
using OfficeOpenXml.DataValidation;
using OfficeOpenXml.Style;

namespace cashbook_psql_cs.util
{
    public static class ExportHelper
    {
        // 导出为 CSV 文件（最简单的方法）
        public static void ExportToCSV(DataGridView dgv, string filePath)
        {
            using (StreamWriter sw = new StreamWriter(filePath, false, Encoding.UTF8))
            {
                // 写入列标题
                var headers = dgv.Columns.Cast<DataGridViewColumn>()
                                  .Select(col => col.HeaderText);
                sw.WriteLine(string.Join(",", headers));

                // 写入数据行
                foreach (DataGridViewRow row in dgv.Rows)
                {
                    if (!row.IsNewRow)
                    {
                        var cells = row.Cells.Cast<DataGridViewCell>()
                                   .Select(c => c.Value?.ToString());
                        sw.WriteLine(string.Join(",", cells));
                    }
                }

                MessageBox.Show("数据已成功导出到: " + filePath);
            }
        }

        // 导出为 Excel（使用 EPPlus 库）
        public static void ExportToExcel(DataGridView dgv, string filePath)
        {
            // 设置许可证上下文为非商业版
            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;

            using (ExcelPackage pck = new ExcelPackage())
            {
                var ws = pck.Workbook.Worksheets.Add("Sheet1");

                // 写入列标题
                for (int i = 0; i < dgv.Columns.Count; i++)
                {
                    ws.Cells[1, i + 1].Value = dgv.Columns[i].HeaderText;
                }

                // 写入数据
                for (int i = 0; i < dgv.Rows.Count; i++)
                {
                    if (!dgv.Rows[i].IsNewRow)
                    {
                        for (int j = 0; j < dgv.Columns.Count; j++)
                        {
                            ws.Cells[i + 2, j + 1].Value = dgv.Rows[i].Cells[j].Value?.ToString();
                        }
                    }
                }

                // 自动调整列宽
                ws.Cells.AutoFitColumns();

                // 保存文件
                FileInfo fi = new FileInfo(filePath);
                pck.SaveAs(fi);

                MessageBox.Show("数据已成功导出到: " + filePath);
            }
        }

        // 导出为 PDF（使用 iTextSharp 库）
        private static void ExportToPDF(DataGridView dgv, string filePath)
        {
            Document doc = new Document(PageSize.A4.Rotate(), 10, 10, 10, 10);

            try
            {
                PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(filePath, FileMode.Create));
                doc.Open();

                PdfPTable table = new PdfPTable(dgv.Columns.Count);
                table.WidthPercentage = 100;

                // 添加列标题
                foreach (DataGridViewColumn column in dgv.Columns)
                {
                    table.AddCell(new Phrase(column.HeaderText, FontFactory.GetFont(FontFactory.HELVETICA_BOLD)));
                }

                // 添加数据行
                foreach (DataGridViewRow row in dgv.Rows)
                {
                    if (!row.IsNewRow)
                    {
                        foreach (DataGridViewCell cell in row.Cells)
                        {
                            table.AddCell(new Phrase(cell.Value?.ToString(), FontFactory.GetFont(FontFactory.HELVETICA)));
                        }
                    }
                }

                doc.Add(table);
                MessageBox.Show("PDF 导出成功: " + filePath);
            }
            catch (Exception ex)
            {
                MessageBox.Show("导出失败: " + ex.Message);
            }
            finally
            {
                doc.Close();
            }
        }

        public static void ExportTemplate()
        {
            // 设置许可证上下文为非商业版
            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;

            using (SaveFileDialog saveDialog = new SaveFileDialog())
            {
                saveDialog.Filter = "Excel Files|*.xlsx";
                saveDialog.FileName = "数据模板.xlsx";

                if (saveDialog.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        using (ExcelPackage package = new ExcelPackage())
                        {
                            // 创建工作表
                            var worksheet = package.Workbook.Worksheets.Add("数据录入");

                            // ========== 设置模板内容 ==========
                            // 1. 设置标题行
                            object[][] headers = new object[][]
                            {
                            new object[] {"序号", "类别", "金额", "分类", "账户", "时间", "成员", "备注"}
                            };

                            worksheet.Cells[1, 1].LoadFromArrays(headers);

                            // 2. 设置列格式
                            worksheet.Column(1).Width = 15;  // 员工编号列宽
                            worksheet.Column(10).Style.Numberformat.Format = "yyyy-mm-dd"; // 日期格式

                            // 3. 设置标题样式
                            using (var headerRange = worksheet.Cells[1, 1, 1, headers.Length])
                            {
                                headerRange.Style.Font.Bold = true;
                                headerRange.Style.Fill.PatternType = ExcelFillStyle.Solid;
                                headerRange.Style.Fill.BackgroundColor.SetColor(Color.LightBlue);
                                headerRange.Style.Border.BorderAround(ExcelBorderStyle.Thin);
                            }

                            // 4. 添加数据验证
                            // 类别下拉列表
                            var validation = worksheet.DataValidations.AddListValidation("B2:B1000");

                            // 直接初始化列表
                            validation.Formula.Values.Add("收入");
                            validation.Formula.Values.Add("支出");

                            // 5. 添加示例数据
                            worksheet.Cells[2, 1].Value = 188;
                            worksheet.Cells[2, 2].Value = "收入";
                            worksheet.Cells[2, 3].Value = "500";
                            worksheet.Cells[2, 4].Value = "生日";
                            worksheet.Cells[2, 5].Value = "现金";
                            worksheet.Cells[2, 6].Value = "2025-03-29";
                            worksheet.Cells[2, 7].Value = "大姐";
                            worksheet.Cells[2, 8].Value = "40岁";

                            // 保存文件
                            package.SaveAs(new FileInfo(saveDialog.FileName));
                            MessageBox.Show("模板导出成功！");
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"导出失败：{ex.Message}");
                    }
                }
            }
        }
    }
}
